/****************************************************
 * Description: ServiceImpl for 私钥信息
 * Copyright:   Copyright (c) 2019
 * Company:     ry
 * @author      reywong
 * @version     1.0
 * @see
	HISTORY
    *  2019-12-13 reywong Create File
**************************************************/

package cn.com.ry.framework.application.meteor.meteor.rsa.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.com.ry.framework.application.meteor.framework.dao.XjjDAO;
import cn.com.ry.framework.application.meteor.framework.service.XjjServiceSupport;
import cn.com.ry.framework.application.meteor.sys.xfile.dao.XfileDao;
import cn.com.ry.framework.application.meteor.sys.xfile.entity.XfileEntity;
import cn.com.ry.framework.application.meteor.framework.exception.ValidationException;



import cn.com.ry.framework.application.meteor.meteor.rsa.entity.RsaEntity;
import cn.com.ry.framework.application.meteor.meteor.rsa.dao.RsaDao;
import cn.com.ry.framework.application.meteor.meteor.rsa.service.RsaService;

import org.apache.commons.lang3.StringUtils;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RsaServiceImpl extends XjjServiceSupport<RsaEntity> implements RsaService {

	@Autowired
	private RsaDao rsaDao;

    @Autowired
    private XfileDao xfileDao;

	@Override
	public XjjDAO<RsaEntity> getDao() {

		return rsaDao;
	}

    /**
    * 导入用户
    * @param fileId
    */
    public Map<String,Object> saveImport(Long fileId) throws ValidationException {
        //校验数据并返回合法数据
        List<RsaEntity> rsaEntityList = this.validImport(fileId);
        if(rsaEntityList==null||rsaEntityList.size()==0){
            throw new ValidationException("文件数据为空，请重新上传");
        }
        int troubleRsaCnt = 0;
        int okCnt = 0;
        //保存数据
        for (int i = 0; i < rsaEntityList.size(); i++) {
            try {
                RsaEntity rsaEntity = rsaEntityList.get(i);
                rsaDao.save(rsaEntity);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ValidationException(e.getMessage());
            }
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("allCnt", rsaEntityList.size());
        map.put("troubleRsaCnt", troubleRsaCnt);
        map.put("okCnt", okCnt);
        return map;
    }

    private List<RsaEntity> validImport(Long fileId) throws ValidationException{
        //获得上传文件
        XfileEntity xfile=xfileDao.getById(fileId);
        if(xfile==null){
            throw new ValidationException("未找到上传文件");
        }
        /**
        * 1.验证上传文件是否为空并且文件格式是否是xls
        */
        String fileName=xfile.getFileRealname();
        String prefix=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        if(!prefix.equals("xls") && !prefix.equals("xlsx")){
            throw new ValidationException("请上传xls或者xlsx格式的文件");
        }
        String[] content = null;
        Workbook workbook = null;
        Sheet sheet = null;
        int length = 0;
        try {
            File file = new File((xfile.getFilePath()));
            workbook = Workbook.getWorkbook(file);
            sheet = workbook.getSheet(0);
            length = sheet.getRows();
        } catch (Exception ex) {
            throw new ValidationException("文件格式转换异常");
        }
        /**
        * 2.验证上传文件中的Excel
        */

        StringBuilder validationMsg = new StringBuilder();
        Cell cell = null;
        int columns = 1;
        if(sheet != null && sheet.getColumns() < columns){
                validationMsg.append("上传失败：上传文件中的Excel列数必须是"+columns+"列。<br/>");
        }
        List<RsaEntity> rsaEntityList=new ArrayList<RsaEntity>();
        /**
        * 3.验证上传文件中的Excel每一行每一列都不为空
        */
        //TODO
        Long id = null;//id
        for (int i = 1; i < length; i++) {// 第2行开始
             content = new String[sheet.getColumns()];
             for (int j = 0; j < columns; j++) {
                  cell = sheet.getCell(j, i);
                  content[j] = cell.getContents().trim();
             }
             if(content[0] ==null || StringUtils.isBlank(content[0])) {
                  validationMsg.append("●文件中第" + (i+1) + "行不能为空。<br/>");
                  continue;
             }

             RsaEntity rsaEntity = new RsaEntity();
             rsaEntity.setId(id);
             rsaEntityList.add(rsaEntity);
        }

        if(!StringUtils.isBlank(validationMsg.toString())) {
             throw new ValidationException(validationMsg.toString());
        }
        return rsaEntityList;
    }


}
